<template>
  <div class="week-create">
    <plan-header ref="planHeader" :tableData="tableData" :openDate="$route.query.openDate"
      :classBtnShow="classBtnShow" />
    <div class="item-border" :style="{backgroundColor: $store.state.user.baseColor}">
      <div class="border"></div>
    </div>
    <div class="plan-body" :style="{backgroundColor: $store.state.user.baseColor}">
      <div class="plan-item" v-for="(item,index) in tableBody" :key="index">
        <div class="item-top">
          <div class="item-name">{{item.name}}</div>
          <div class="item-btn">
            <el-button @click="planTemplate(item)" size="small" icon="iconfont icon-05_11hetongmobanshenpichaxun"
              type="primary"> 模板</el-button>
            <el-button @click="planRecord(item)" size="small" icon="iconfont icon-biaoshileijihuamoban" type="primary">
              撰写记录</el-button>
          </div>
        </div>
        <div class="input" v-if="item.style=='summerNote'">
          <tinymce :editorRef="item.style+'-'+item.docDefId" :ref="item.style+'-'+item.docDefId" v-model="content[item.style+'-'+item.docDefId]" @contentData="quillChange($event)" :height="400">
          </tinymce>
        </div>
        <div class="input" v-else>
          <el-input v-model="content[item.style+'-'+item.docDefId]"></el-input>
        </div>
        <div class="item-border" :style="{backgroundColor: $store.state.user.baseColor}">
          <div class="border"></div>
        </div>
      </div>
      <el-button class="save" @click="save" size="small" type="primary" icon="iconfont icon-save"
        v-loading.fullscreen.lock="loading" element-loading-text="保存中"> 保 存</el-button>
      <el-button v-if="docDataId" class="print" @click="printModalShow" type="primary" icon="el-icon-printer"
        size="small">打印</el-button>
      <!-- 打印 -->
      <vxe-modal v-model="printModal" title="预览" height="80%" show-zoom resize width="600" show-footer>
        <template #default>
          <weekPlanPrint id="myPrint" :previewData="previewData" :docClassId="docClassId" />
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
        </template>
      </vxe-modal>
      <!-- 撰写记录 -->
      <vxe-modal v-model="planRecordShow" title="撰写记录" height="500" show-zoom resize width="500" :mask="false"
        :lockView="false">
        <template #default>
          <planRecord :docItemDefId="planRecordCurrentDocItemDefId" :currentStyle="currentStyle"
            @getplanRecordName="getplanRecordName" />
        </template>
      </vxe-modal>
      <!-- 模板 -->
      <vxe-modal v-model="templateShow" title="周训练计划模板" height="80%" show-zoom resize width="800" :mask="false" @close="templateCloseWatch"
        :lockView="false">
        <template #default>
          <planTemplate ref="planTemplate" :docItemDefId="currentDocItemDefId" :sportId="currentSportId" @getTemplateName="getTemplateName"
            :empId="empId" @templateClose="templateClose" />
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import {
    weekPlan,
    insertDocData,
    planSave,
    updateDocData,
    getContent,
    allType
  } from "@/api/plan.js"
  import planHeader from "@/components/plan/planHeader.vue"
  import Tinymce from "@/components/Tinymce"
  import weekPlanPrint from "@/components/print/weekPlanPrint.vue"
  import planRecord from "@/components/plan/planRecord.vue"
  import planTemplate from "@/components/plan/planTemplate.vue"
  export default {
    components: {
      planHeader,
      Tinymce,
      weekPlanPrint,
      planRecord,
      planTemplate
    },
    data() {
      return {
        docClassId: '',
        docDataId: '',
        tableData: {},
        tableBody: [],
        content: {},
        statusId: 1,
        loading: false,
        classBtnShow: true,
        printModal: false,
        previewData: {},
        planRecordShow: false,
        currentDocItemDefId: '',
        planRecordCurrentDocItemDefId: '',
        currentStyle: '',
        templateShow: false,
        currentSportId: '',
        templateStr: '',
        empId: '',
      }
    },
    created() {
      this.docDataId = this.$route.query.docDataId
      this.getPlanData()
    },
    methods: {
      templateCloseWatch() {
        this.$refs.planTemplate.closeTemplate()
      },
      quillChange({content,key}) {
        this.content[key] = content
      },
      templateClose() {
        this.templateShow = false
      },
      getTemplateName(str) {
        let key = this.currentStyle + '-' + this.currentDocItemDefId
        if (this.currentStyle == 'summerNote') {
          this.templateStr = this.content[key]+str
          this.$refs[key][0].setContent(this.templateStr)
        } else {
          str = str.replace(new RegExp("<p>", "gm"), "");
          str = str.replace(new RegExp("</p>", "gm"), "");
          this.templateStr = this.content[key] + str
          this.content[key] = this.templateStr
        }
        this.$message.success('内容已添加到编辑区')
      },
      planTemplate(item) {
        this.currentDocItemDefId = item.docDefId
        this.currentStyle = item.style
        this.currentSportId = this.$refs.planHeader.planForm.sportId
        this.empId = this.$refs.planHeader.planForm.empId
        this.templateShow = true
      },
      getplanRecordName(item) {
        let key = this.currentStyle + '-' + item.docItemDefId
        if (this.currentStyle == 'summerNote') {
          // this.content[key] = item.content
          this.$refs[key][0].setContent(item.content)
        } else {
          this.content[key] = item.val
        }
      },
      planRecord(item) {
        this.planRecordCurrentDocItemDefId = item.docDefId
        this.currentStyle = item.style
        this.planRecordShow = true
      },
      printEvent() {
        const divEl = document.getElementById('myPrint')
        const printStyle = `
				#myPrint{
				  color: #000;
				}
         p{
           margin: 4px 0;
         }
       `
        this.$XPrint({
          sheetName: '',
          style: printStyle,
          content: divEl.innerHTML
        })
      },
      printModalShow() {
        allType({
          docDataId: this.docDataId,
          docClassId: this.docClassId
        }).then(res => {
          if (res.code === 200) {
            this.previewData = res.data
            this.printModal = true
          } else {
            this.$message.error(res.message)
          }
        })
      },
      save() {
        this.loading = true
        let headerData = this.$refs.planHeader.planForm
        let doubleDate = this.$refs.planHeader.doubleDate
        let json = {
          openDate: doubleDate[0] + ' 00:00:00',
          closeDate: doubleDate[1] + ' 00:00:00',
          name: headerData.name,
          empId: headerData.empId,
          docDataEmp: headerData.docDataEmpId.join(','),
          createDate: this.$moment(headerData.createDate).format('YYYY-MM-DD') + ' 00:00:00',
          docClassId: this.docClassId,
          statusId: 1,
        }
        if(headerData.sportId) json.sportId = headerData.sportId
        if (headerData.sportItemId) json.sportItemId = headerData.sportItemId
        if (this.docDataId) {
          json['docDataId'] = this.docDataId
          // 先修改头
          updateDocData(json).then(res => {
            if (res.code === 200) {
              // 再修改身体
              this.planBodySave(headerData)
            } else {
              this.loading = false
              this.$message.error(res.message)
            }
          })
        } else {
          json['parentId'] = -1
          // 先保存头
          insertDocData(json).then(res => {
            if (res.code === 200) {
              this.docDataId = res.data.docDataId
              // 再保存身体
              this.planBodySave(headerData)
            } else {
              this.$message.error(res.message)
            }
          })
        }
        this.loading = false
      },
      planBodySave(headerData) {
        let data = []
        for (let key in this.content) {
          let type = key.split('-')
          if (this.content[key]) {
            this.content[key] = this.content[key].replace(/\n/g, "");
          }
          if (type[0] == 'summerNote') {
            data.push({
              content: this.content[key],
              createDate: this.$moment(headerData.createDate).format('YYYY-MM-DD'),
              docClassId: this.docClassId,
              docDataId: this.docDataId,
              docItemDefId: type[1],
              docItemTypeId: "1",
              empId: headerData.empId,
              statusId: this.statusId,
              val: ""
            })
          } else {
            data.push({
              content: "",
              createDate: this.$moment(headerData.createDate).format('YYYY-MM-DD'),
              docClassId: this.docClassId,
              docDataId: this.docDataId,
              docItemDefId: type[1],
              docItemTypeId: "1",
              empId: headerData.empId,
              statusId: this.statusId,
              val: this.content[key],
            })
          }
        }
        planSave(data).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 0,
              position: 'bottom-right'
            });
            this.$message.success('数据保存成功.!')
            this.$router.push({
                query:{
                    docDataId:this.docDataId
                }
            })
          } else {
            this.$message.error(res.message)
          }
          this.loading = false
        })
      },
      getPlanContent() {
        getContent({
          docDataId: this.docDataId
        }).then(res => {
          if (res.code === 200) {
            this.tableData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
      },
      date_dict(date) {
        let d = this.$moment(date);
        this.$moment.defaultFormat = "YYYY-MM-DD";
        return {
          '星期一': d.add(0, "d").format(),
          '星期二': d.add(1, "d").format(),
          '星期三': d.add(1, "d").format(),
          '星期四': d.add(1, "d").format(),
          '星期五': d.add(1, "d").format(),
          '星期六': d.add(1, "d").format(),
          '星期日': d.add(1, "d").format(),
        }
      },
      getPlanData() {
        if (this.docDataId) {
          getContent({
            docDataId: this.docDataId
          }).then(res => {
            if (res.code === 200) {
              this.tableData = res.data
              this.tableData.parentId = this.docDataId
              this.docClassId = res.data.planTypeId
              this.tableBody = res.data.tableBody
              let tableHeader = res.data.tableHeader
              let openDate = tableHeader[1].openDate
              let dict_date = this.date_dict(openDate)
              this.tableBody.forEach(item => {
                let str = item.name.substr(0, 3)
                item.name = item.name + (dict_date[str] ? '(' + dict_date[str] + ')' : '')
                if (item.style == 'summerNote') {
                  this.$set(this.content, item.style + '-' + item.docDefId, item.content)
                } else {
                  this.$set(this.content, item.style + '-' + item.docDefId, item.val)
                }
              })
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          this.classBtnShow = false
          weekPlan().then(res => {
            if (res.code === 200) {
              this.tableData = res.data
              this.docClassId = res.data.planTypeId
              this.tableBody = res.data.tableBody
              let openDate = this.$route.query.openDate.split('至')[0]
              let dict_date = this.date_dict(openDate)
              this.tableBody.forEach(item => {
                let str = item.name.substr(0, 3)
                item.name = item.name + (dict_date[str] ? '(' + dict_date[str] + ')' : '')
                this.$set(this.content, item.style + '-' + item.docDefId, '')
              })
            } else {
              this.$message.error(res.message)
            }
          })
        }
      }
    },
    beforeDestroy() {
      this.$notify.closeAll()
    }
  }
</script>

<style lang="scss" scoped>
  .week-create {
    .plan-body {
      background-color: #FFFFFF;

      .plan-item {
        width: 100%;
        padding: 10px 0;

        .item-top {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 250px;

          .item-name {
            font-size: 120%;
          }
        }

        .input {
          padding: 10px 250px;
        }
      }
    }

    .item-border {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #FFFFFF;

      .border {
        height: 1px;
        width: 90%;
        background-image: linear-gradient(to right, #fff, #c7c7c7, #fff);
        margin: 20px auto;
      }
    }

    .save {
      position: fixed;
      bottom: 50px;
      right: 50px;
    }

    .print {
      position: fixed;
      top: 150px;
      right: 50px;
    }
  }
</style>
